<script lang="ts" setup>
import type { StateType } from './types';

import { computed } from 'vue';
import { useRoute } from 'vue-router';
import { $t } from '@vben/locales';
import { Page } from '@vben/common-ui';
import { useTabs } from '@vben/hooks';
import draggable from 'vuedraggable';
import { useTitle } from '@vueuse/core';
import {
  Card,
  message,
  Select,
  SelectOption,
  TabPane,
  Tabs,
  Modal,
  FormItem,
  Form,
  Input,
  Checkbox,
  RadioGroup,
  Radio,
  
  
} from 'ant-design-vue';
import { UEditor } from '#/components/UEditor';
import dayjs from 'dayjs';
import { storeToRefs } from 'pinia';
import { pinyin } from 'pinyin-pro';

import { useVbenForm } from '#/adapter/form';
import { getFormConcatInfo, postFormConcat, putFormConcat } from '#/api/admin/formconcat';

import { usePreferencesStore } from '#/store';
import Button from '../../../../../../packages/@core/ui-kit/shadcn-ui/src/components/button/button.vue';


const route = useRoute();

const { setTabTitle, closeCurrentTab } = useTabs();

const index: any = computed(() => {
  return route.params?.id ?? -1;
});
const router = useRouter();
const routeMeta = router.currentRoute.value.meta;
const routeTitle = routeMeta.title.replace('管理', '');
const preferencesStore = usePreferencesStore();
const { title } = storeToRefs(preferencesStore);
const fieldTypeOptions = [
  { label: '输入框', value: 'input' },
  { label: '选择器', value: 'select' },
  { label: '日期', value: 'date' },
  { label: '富文本', value: 'textarea' },
  { label: '邮箱', value: 'email' },
  { label: '国家', value: 'country' },
  { label: '省份', value: 'state' },
  { label: '单选框', value: 'radio' },
  { label: '复选框', value: 'checkbox' },
  { label: '提交按钮', value: 'submit' },
];


const pageTitle =
  Number.parseInt(index.value, 10) === 0
    ? `新增${routeTitle}`
    : `No.${index.value} - 编辑${routeTitle}`;
setTabTitle(pageTitle);
useTitle(`${pageTitle} - ${title.value}`);

const disabled = ref(true);

const state: StateType = reactive({
  form: {
    title: '',
    des: '',
    content: '',  
    template_id:''
  },
});

const [BasicForm, BasicFormApi] = useVbenForm({
  handleSubmit: onSubmit,
  resetButtonOptions: {
    show: false,
  },
  schema: [
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: ['id'],
      },
      fieldName: 'id',
      label: 'ID',
    },
    {
      component: 'Input',
      defaultValue: '',
      dependencies: {
        trigger: (values) => {
          disabled.value = !values.title;
          state.form.content = values.content;
          state.form.title = values.title;
          state.form.des = values.des;
          state.form.status = values.status;
          state.form.template_id = values.template_id
        },
        // 随意一个字段改变时，都会触发
        triggerFields: [
          'id',
          'title',
          'des',
          'status',
          'content',
          'template_id'
        ],
      },
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'title',
      label: `${routeTitle} `+$t('page.common.Title'),
      rules: 'required',
    },
    {
      component: 'RadioGroup',
      componentProps: {
        options: [
          {
            label: 'Publish',
            value: 1,
          },
          {
            label: 'Trash',
            value:  0,
          },
          
        ],
      },
      fieldName: 'status',
      rules: 'required', 
      label: $t('page.common.Status'),
    },


    {
      component: 'Textarea',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
        autosize: { minRows: 3, maxRows: 18 }, // 自动高度范围
      },
      fieldName: 'des',
      label: `${routeTitle} `+$t('page.common.Description'),
    },
     {
      component: 'content',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'content',
      label: $t('page.common.Content'),
    },
    

  ],
});




  const tag1 = ref([]);
async function onSubmit() {
  function showMsg(msg: string) {
    message.success(msg);
    closeCurrentTab();
      router.push({
          name: `AdminForm`,
     });
  }
  const values: any = state.form;

  if (values.id) {
    const { msg } = await putFormConcat(values);
    showMsg(msg);
  } else {
    delete values.id;
    const { msg } = await postFormConcat(values);
    showMsg(msg);
  }
}
async function onGetPage(id: number) {
 
  const { data } = await getFormConcatInfo(id);
  
  data.post = {
    id: data?.id ?? undefined,
    title: data?.title ?? '',
    des: data?.des ?? '',
    content:  data?.content ?? '',
    status: data?.status ?? '',
    template_id:data?.template_id??'',
   
  };
  state.form = data.post;
  tag1.value = data?.tags??[]
  BasicFormApi.setValues({ ...state.form});




         

}

onMounted(async () => {
  if(index.value>0){
  
        await onGetPage(index.value);
        await onGetPage_email();

  }
  
});

////插入标签的

const input_type= ref();
const tag =ref();
const form = ref({
   form_require: false,
   form_name: '',
   form_type:'',
   form_placeholder: '',
   form_ID: '',
   form_class: '',
   questions:{
    tips:'',
    question:'',
    question_modal:'',
    option:'',
   }
});
input_type.value=[
  'text','email','select','radio','checkbox','textarea','question','country','state','captcha'
];
const input_type_selected=ref('');
const is_input_type_modal = ref(false);
const selectInputType = async  (item: string) => {

   const values = await BasicFormApi.getValues();
   const currentText = values['content'] || ''; // 假设字段名是 content
   const select_text = currentText.substring(cursorPosition.value, cursorPositionend.value)
   tag.value =select_text
   console.log(select_text)
    form.value =parseTagToForm(tag.value)
 



  input_type_selected.value=item;
  is_input_type_modal.value = true;
  form.value.form_type = item;

};


const parseTagToForm = (tag: string) => {
  const cleanTag = tag.replace(/^\[|\]$/g, '').trim();

  const formData = {
    form_require: false,
    form_name: '',
    form_type: '',
    form_placeholder: '',
    form_ID: '',
    form_class: '',
    questions: {
      tips: '',
      question: '',
      question_modal: '',
      option: '',
    }
  };

  const fields = [
    'type-', 'name-', 'class-', 'id-', 'placeholder-', 'question_modal-',
    'question_answer-', 'question_tips-', 'question_option-', 'require'
  ];

  // 按顺序提取各个字段（包括可能带空格的值）
  const result: Record<string, string[]> = {};
  for (const field of fields) {
    const regex = new RegExp(`${field}([^\\[]+?)(?=(\\s+${fields.join('|')})|$)`, 'g');
    let match;
    while ((match = regex.exec(cleanTag)) !== null) {
      if (!result[field]) result[field] = [];
      result[field].push(match[1].trim());
    }
  }
  console.log(result)

  // 填入数据
  if (result['type-']) formData.form_type = result['type-'][0];
  if (result['name-']) formData.form_name = result['name-'][0];
  if (result['class-']) formData.form_class = result['class-'][0];
  if (result['id-']) formData.form_ID = result['id-'][0];
  if (result['placeholder-']) formData.form_placeholder = result['placeholder-'][0];
  if (result['question_modal-']) formData.questions.question_modal = result['question_modal-'][0];
  if (result['question_tips-']) formData.questions.tips = result['question_tips-'][0];
  if (result['question_answer-']) formData.questions.question = result['question_answer-'][0];
  if (result['question_option-']) formData.questions.option = result['question_option-'].join('\n');
  if (cleanTag.includes('require')) formData.form_require = true;

  return formData;
};


const form_change = ()=>{
console.log(form.value)
    tag.value ="[";
    if(form.value.form_type){
       tag.value+=' type-'+form.value.form_type+' ';
    }

     if(form.value.form_name){
       tag.value+=' name-'+form.value.form_name+' ';
    }


    if(form.value.form_class){
       tag.value+=' class-'+form.value.form_class+' ';
    }
   
    if(form.value.form_ID){
        tag.value+=' id-'+form.value.form_ID+' ';
    }

     if(form.value.form_require){
        tag.value+=' require';
    }
    
     if(form.value.form_placeholder){
        tag.value+=' placeholder-'+form.value.form_placeholder+' ';
    }
     if(form.value.questions.question_modal){
        tag.value+=' question_modal-'+form.value.questions.question_modal;
    }

     if(form.value.questions.tips){
        tag.value+=' question_tips-'+form.value.questions.tips;
    }

    
     if(form.value.questions.question){
        tag.value+=' question_answer-'+form.value.questions.question;
    }



    if (form.value.questions.option) {
        const lines = form.value.questions.option.split('\n') // 按行分割
          .filter(line => line.trim() !== '') // 去除空行
          .map(line => `question_option-${line.trim()}`); // 每行加上前缀和双引号
        tag.value += ' ' + lines.join(' '); // 用空格拼接
      }
    
    tag.value+="]";
   
}



const textareaRef = ref<HTMLTextAreaElement | null>(null);

const cursorPosition = ref(0);
const cursorPositionend =ref(0)
const text = ref('');

const updateCursorPosition = (e) => {
   cursorPosition.value = e.target.selectionStart;
   cursorPositionend.value = e.target.selectionEnd;
};


const handleOk = () => {
  insertTag();
  is_input_type_modal.value = false;
};

const handleCancel = () => {
  // 点击取消或关闭弹窗时
  is_input_type_modal.value = false;
};



// 插入 tag 到指定位置
const insertTag = async () => {
  const values = await BasicFormApi.getValues();
  const currentText = values['content'] || ''; // 假设字段名是 content
  const pos_end =cursorPositionend.value;
  const pos = cursorPosition.value;
  let newText='';
  if(pos_end == pos){
   newText = currentText.slice(0, pos) + tag.value + currentText.slice(pos);
  }else{
   newText = currentText.slice(0, pos) + tag.value + currentText.slice(pos_end);
  }


  await BasicFormApi.setFieldValue('content', newText);
  tag.value='';
  input_type_selected.value='';
  form.value ={
   form_require: false,
   form_name: '',
   form_type:'',
   form_placeholder: '',
   form_ID: '',
   form_class: '',
   questions:{
    tips:'',
    question:'',
    question_modal:'',
    option:'',
   }
};
 

  // nextTick(() => {
  //   const textarea = textareaRef.value;
  //   if (textarea) {
  //     const newPos = pos + tag.value.length;
  //     textarea.setSelectionRange(newPos, newPos);
  //     textarea.focus();
  //     cursorPosition.value = newPos;
  //   }
  // });
};



//tab 


const activeKey = ref('1');

//邮件模版
const stateemail: StateType = reactive({
  form: {
    title: '',
    des: '',
    content:''
   
  },
  pageThemeFiles: [],
});
import { getEmailTemplatInfo, postEmailTemplat, putEmailTemplat } from '#/api/admin/emailTemplate';
const [EmailForm, EmailFormApi] = useVbenForm({
  handleSubmit: onSubmitemail,
  resetButtonOptions: {
    show: false,
  },
  schema: [
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: ['id'],
      },
      fieldName: 'id',
      label: 'ID',
    },
    {
      component: 'Input',
      defaultValue: '',
      dependencies: {
        trigger: (values) => {
          disabled.value = !values.title;
          stateemail.form.content = values.content;
          stateemail.form.title = values.title;
          stateemail.form.status = values.status;
        },
        // 随意一个字段改变时，都会触发
        triggerFields: [
          'id',
          'title',
          'status',
          'content',
        ],
      },
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'title',
      label: `${routeTitle} `+$t('page.common.Title'),
      rules: 'required',
    },
    {
      component: 'RadioGroup',
      componentProps: {
        options: [
          {
            label: 'Publish',
            value: 1,
          },
          {
            label: 'Trash',
            value:  0,
          },
          
        ],
      },
      fieldName: 'status',
      rules: 'required', 
      label: $t('page.common.Status'),
    },
    {
         component: 'tag',
         label:$t('admin.clickToCopy'),
         fieldName: 'tag',
    },
    {
      component: 'Editor',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'content',
      label: $t('page.common.Content'),
    },
  ],
});
 function showMsg(msg: string) {
    message.success(msg);
   
  }
  
async function onSubmitemail() {
 
  const values: any = stateemail.form;
values.form_id=index.value;
  if (values.id) {
    const { msg } = await putEmailTemplat(values);
    showMsg(msg);
  } else {
    const { msg } = await postEmailTemplat(values);
    showMsg(msg);
  }
}


async function onGetPage_email() {
  const { data } = await getEmailTemplatInfo({form_id:index.value});
  data.post = {
    id: data?.id ?? undefined,
    title: data?.title ?? '',
    content: data?.content ?? '',
    status: data?.status ?? '',
  };
  stateemail.form = data.post;
  EmailFormApi.setValues({ ...stateemail.form});
  
}
const copySuccess = ref(false);

function copyText(text) {
  // 使用 Clipboard API 进行复制
  navigator.clipboard.writeText(text).then(() => {
    copySuccess.value = true; // 显示复制成功提示
     showMsg('复制成功');
  }).catch(() => {
    console.error('复制失败');
  });
}
</script>

<template>
  <Page>
    <Card :title="`${routeTitle} `+$t('page.common.Details')">
     

      <Tabs v-model:active-key="activeKey">
        <TabPane key="1" force-render :tab="$t('admin.formConfig')">
            <BasicForm>
              
              <template #content="slotProps" >
                  <div class="w-full">
                    <div class="flex pb-6" style="gap:1rem">
                        <Button v-for="item in input_type" @click="selectInputType(item)">{{ item }}</Button>
                  </div>
                  <textarea  v-bind="slotProps" v-model="text"  ref="textareaRef"  class="w-full border p-3"  style="min-height: 500px;"
                             @input="e => { slotProps.onInput?.(e); updateCursorPosition(e); }"
                              @click="e => { slotProps.onClick?.(e); updateCursorPosition(e); }"
                              @keyup="e => { slotProps.onKeyup?.(e); updateCursorPosition(e); }">
                  
                  
                  </textarea>
                  </div>
                </template>
            </BasicForm>
       
       
        </TabPane>
        <TabPane key="2"  :tab="$t('page.menu.Email Templates')">
         
            <EmailForm>
               <template #tag="slotProps">
                  <div class="w-full" v-bind="slotProps">
                          <div class="flex pb-6 mt-7" style="gap:1rem;flex-wrap: wrap;">
                              <Button @click="copyText('[' + item + ']')" v-for="item in tag1" :key="item">{{ item }}</Button>
                        </div>
                    </div>
               </template>
               


            </EmailForm>
      
             
        </TabPane>

 
   
  
      </Tabs>


  
    </Card>
   <Modal
      v-model:visible="is_input_type_modal"
      title="表单字段"
      :width="'800px'"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <Form
        ref="formRef"
        :model="form"
        class="w-full"
        :label-col="{ span: 5 }"
        :wrapper-col="{ style: { flex: 1 } }"
        @change = "form_change"

      >
        <FormItem label="字段类型">
          <Checkbox v-model:checked="form.form_require"  @change="form_change">必填字段</Checkbox>
        </FormItem>
         <FormItem label="类型">
          <Input name="form_name" v-model:value="form.form_type" disabled class="w-full border pl-2" @input="form_change"/>
        </FormItem>
        <FormItem label="问题" v-if="input_type_selected == 'question'">
          <Input  name="form_name" v-model:value="form.questions.question" placeholder="请输入问题" class="w-full border pl-2" @input="form_change"/>
        </FormItem>
           <FormItem label="提示" v-if="input_type_selected == 'question'">
          <textarea  name="form_name" v-model="form.questions.tips" placeholder="tips" class="w-full border pl-2" @input="form_change"></textarea>
        </FormItem>

         <FormItem label="问题模式" v-if="input_type_selected == 'question'">
          <RadioGroup v-model:value="form.questions.question_modal" @change="form_change" class="w-full">
            <Radio value="single" class="mr-4">单选</Radio>
            <Radio value="multiple" class="mr-4">复选</Radio>
            <Radio value="textarea">Textarea</Radio>
          </RadioGroup>
      

        
        </FormItem>
         <FormItem label="选项" v-if="input_type_selected=='radio' || input_type_selected=='checkbox' || input_type_selected == 'question'">
          <textarea  name="form_name" v-model="form.questions.option" style="height:7rem" placeholder="每行一个选项" class="w-full border pl-2" @input="form_change"></textarea>
        </FormItem>


        <FormItem label="名字">
          <Input  name="form_name" v-model:value="form.form_name" placeholder="请输入名字" class="w-full border pl-2" @input="form_change"/>
        </FormItem>
         <FormItem label="请输入">
          <Input  name="form_placeholder" v-model:value="form.form_placeholder"  placeholder="请输入提示" class="w-full border pl-2" @input="form_change"/>
        </FormItem>
         <FormItem label="ID">
          <Input name="form_ID" v-model:value="form.form_ID"  placeholder="请输入ID" class="w-full border pl-2" @input="form_change"/>
        </FormItem>
         <FormItem label="class">
          <Input name="form_class" v-model:value="form.form_class"  placeholder="请输入class" class="w-full border pl-2" @input="form_change"/>
        </FormItem>
        

        <Textarea  class="w-full border pl-2" v-model:value="tag">
        
        </Textarea>
    
       
      </Form>
    </Modal>



     
  </Page>
</template>

